Collections IS311. The Collections Framework. Type Trees for Collections. Java Collections Framework (ต อ)

Size: px
Start display at page:

Download "Collections IS311. The Collections Framework. Type Trees for Collections. Java Collections Framework (ต อ)"

Transcription

1 IS311 Java Collections Framework (ต อ) Collections Collections are holders that let you store and organize objects in useful ways for efficient access. In the package java.util, there are interfaces and classes that provide a generic collection framework. The Collections interfaces: Collection<E>, Set<E>, SortedSet<E>, List<E>, Queue<E>, Map<K,V>, SortedMap<K,V>, Iterator<E>, ListIterator<E>, Iterable<E> Some useful implementations of the interfaces: HashSet<E>, TreeSet<E>, ArrayList<E>, LinkedList<E>, HashMap<K,V>, TreeMap<K,V>, WeakHashMap<K,V> Exceptions: UnsupportedOperationException ClassCastException IllegalArgumentException NoSuchElementException NullPointerException 1 2 Type Trees for Collections The Collections Framework Iterable<E> Collection<E> Set<E> Queue<E> List<E> SortedSet<E> EnumSet<E> PriorityQueue<E> HashSet<E> TreeSet<E> Iterator<E> ListIerator<E > ArrayList<E> LinkedList<E> The Java collection framework is a set of generic types that are used to create collection classes that support various ways to store and manage objects of any kind in memory. A generic type for collection of objects: To get static checking by the compiler for whatever types of objects to want to manage. Generic Types Generic Class/Interface Type The Iterator<T> interface type Description Declares methods for iterating through elements of a collection, one at a time. LinkedHashSet<E> SortedMap<K,V> Map<K,V> EnumMap<K,V> WeakHashMap<K,V> HashMap<E> The Vector<T> type The Stack<T> type The LinkedList<T> type Supports an array-like structure for storing any type of object. The number of objects to be stored increases automatically as necessary. Supports the storage of any type of object in a pushdown stack. Supports the storage of any type of object in a doubly-linked list, which is a list that you can iterate though forwards or backwards. TreeMap<K,V> LinkedHashMap<K,V> The HashMap<K,V> type Supports the storage of an object of type V in a hash table, sometimes called a map. The object is stored using an associated key object of type K. To retrieve an object you just supply its associated key. 3 4

2 Collections of Objects Collections of Objects Three Main Types of Collections Sets Sets Sequences Maps The simple kinds of collection The objects are not ordered in any particular way. The objects are simply added to the set without any control over where they go. Sequences The objects are stored in a linear fashion, not necessarily in any particular order, but in an arbitrary fixed sequence with a beginning and an end. Collections generally have the capability to expand to accommodate as many elements as necessary. The various types of sequence collections Array or Vector LinkedList Stack Queue 5 6 Maps Collections of Objects Each entry in the collection involves a pair of objects. A map is also referred to sometimes as a dictionary. Each object that is stored in a map has an associated key object, and the object and its key are stored together as a name-value pair. Comparable and Comparator The interface java.lang.comparable<t> can be implemented by any class whose objects can be sorted. public int compareto (T other): return a value that is less than, equal to, or greater than zero as this object is less than, equal to, or greater than the other object. If a given class does not implement Comparable or if its natural ordering is wrong for some purpose, java.util.comparator object can be used public int compare(t o1, T o2) boolean equals(object obj) 7 8

3 The Collection Interface Collection Classes The Collection Interface The basis of much of the collection system is the Collection interface. Methods: public int size() public boolean isempty() public boolean contains(object elem) public Iterator<E> iterator() public Object[] toarray() public <T> T[] toarray(t[] dest) public boolean add(e elem) public boolean remove(object elem) public boolean containsall(collection<?> coll) public boolean addall(collection<? extends E> coll) public boolean removeall(collection<?> coll) public boolean retainall(collection<?> coll) public void clear() Classes in Sets: HashSet<T> LinkedHashSet<T> TreeSet<T> EnumSet<T extends Enum<T>> Classes in Lists: To define a collection whose elements have a defined ordereach element exists in a particular position the collection. Vector<T> Stack<T> LinkedList<T> ArrayList<T> Class in Queues: FIFO ordering PriorityQueue<T> Classes in Maps: Does not extend Collection because it has a contract that is different in important ways: do not add an element to a Map(add a key/value pair), and a Map allows looking up. Hashtable<K,V> HashMap<K,V> LinkedHashMap<K,V> WeakHashMap<K,V> IdentityHashMap<K,V> TreeMap<K,V> : keeping its keys sorted in the same way as TreeSet 9 10 Sets The simple kinds of collection The objects are not ordered in any particular way. The objects are simply added to the set without any control over where they go. Contains no methods other than those inherited from Collection Iterator The elements are traversed in no particular order Tree of Sets Iterable<E> Collection<E> Set<E> SortedSet<E> HashSet<E> EnumSet<E> TreeSet<E> LinkedHashSet<E> 11 12

4 boolean add(e e) interface Set<E> boolean addall(collection<? extends E> c) void clear( ) boolean contains(object o) boolean containsall(collection<?> c) boolean isempty( ) Iterator iterator( ) boolean remove(object o) boolean retainall(collection <?> c) int size( ) Object [] toarray() <T> T[] toarray(t[] a) interface SortedSet<E> SortedSet a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls. Iterator The elements are traversed according to the natural ordering (ascending) public interface SortedSet<E> extends Set<E> { // Range-view SortedSet<E> subset(e fromelement, E toelement); SortedSet<E> headset(e toelement); SortedSet<E> tailset(e fromelement); // Endpoints E first(); E last(); interface SortedSet<E> // Comparator access Comparator<? super E> comparator(); Set implementations HashSet implements Set Hash tables as internal data structure (faster) LinkedHashSet extends HashSet Elements are traversed by iterator according to the insertion order TreeSet implements SortedSet red-black tree structure (R-B trees) as internal data structure (computationally expensive) 15 16

5 HashSet LinkedHashSet Implement the interface Set. Implemented using a hash table. อ อบเจ กท ท จะนำมาบรรจ ในเซตชน ดน ได ต องมาจากคลาสท ม กา รอ มพล เม นท เมท อด hashcode() No ordering of elements. add, remove, and contains methods constant time complexity O(c). extend HashSet with linked list implementation support ordering of elements (ตามลำด บท เพ มเข าไป) add, remove, and contains methods linear time complexity O(n), where n is the number of elements in the set TreeSet Implement the interface Set. Implemented using tree structure. Guarantees ordering of elements. add, remove, and contains methods logarithmic time complexity O(log (n)), where n is the number of elements in the set. Maps Map (key, value) binding No duplicate keys Examples identity code (String), person (Person) student ID (Integer), student (Student) 19 20

6 Maps Tree of Maps Each entry in the collection involves a pair of objects. A map is also referred to sometimes as a dictionary. Each object that is stored in a map has an associated key object, and the object and its key are stored together as a name-value pair. Maps do not have an iterator SortedMap<K,V> TreeMap<K,V> Map<K,V> HashMap<E> LinkedHashMap<K,V> EnumMap<K,V> WeakHashMap<K,V> Classes in Maps Does not extend Collection because it has a contract that is different in important ways: do not add an element to a Map(add a key/value pair), and a Map allows looking up. Hashtable<K,V> HashMap<K,V> LinkedHashMap<K,V> WeakHashMap<K,V> IdentityHashMap<K,V> TreeMap<K,V> : keeping its keys sorted in the same way as TreeSet interface Map<K,V> Map an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value

7 interface Map<K,V> interface SortedMap<K,V> public interface Map<K,V> { // Basic operations V put(k key, V value); V get(object key); V remove(object key); boolean containskey(object key); boolean containsvalue(object value); int size(); boolean isempty(); // Bulk operations void putall(map<? extends K,? extends V> m); void clear(); // Collection Views public Set<K> keyset(); public Collection<V> values(); public Set<Map.Entry<K,V>> entryset(); // Interface for entryset elements public interface Entry { K getkey(); V getvalue(); V setvalue(v value); public interface SortedMap<K, V> extends Map<K, V>{ SortedMap<K, V> submap(k fromkey, K tokey); SortedMap<K, V> headmap(k tokey); SortedMap<K, V> tailmap(k fromkey); K firstkey(); K lastkey(); Comparator<? super K> comparator(); HashMap and TreeMap Classes The HashMap and HashTree classes implement the Map interface. HashMap The implementation is based on a hash table. No ordering on (key, value) pairs. TreeMap The implementation is based on R-B trees structure (key, value) pairs are ordered on the key. Comparable and Comparator The interface java.lang.comparable<t> can be implemented by any class whose objects can be sorted. public int compareto (T other): return a value that is less than, equal to, or greater than zero as this object is less than, equal to, or greater than the other object. If a given class does not implement Comparable or if its natural ordering is wrong for some purpose, java.util.comparator object can be used public int compare(t o1, T o2) boolean equals(object obj) 27 28

8 Enhanced for loop If a class extends Iterable<E> you can use Java's enhanced for loop of this general form for (E refvar : collection<e> ) { refvar refers to each element in collection<e> example ArrayList<String> list = new ArrayList<String>(); list.add("first"); list.add("second"); for (String s : list) System.out.println(s.toLowerCase()); Algorithms Java has polymorphic algorithms to provide functionality for different types of collections Sorting (e.g. sort) Shuffling (e.g. shuffle) Routine Data Manipulation (e.g. reverse, addall) Searching (e.g. binarysearch) Composition (e.g. frequency) Finding Extreme Values (e.g. max) Algorithms All of the algorithms, provided by the Collections class, take the form of static methods Most of the algorithms operate on List objects, but a couple of them (max and min) operate on arbitrary Collection objects Collections static methods Static library with many useful algorithms Searching int pos = Collections.binarySearch(list, key); Counting int f = Collections.frequency(myColl, item); Sorting... Collections.sort(list); Collections.sort(list, comparator); Max, Min, Shuffling, reversing, performing set operations and much more 31 32

9 Sorting The sort operation uses a slightly optimized merge sort algorithm Fast: This algorithm is guaranteed to run in n log(n) time, and runs substantially faster on nearly sorted lists. Stable: That is to say, it doesn't reorder equal elements. ต วอย างการใช เมท อด sort ของ Collections import java.util.*; public class SortDemo { public static void main( String args[] ) { List <String> l = new ArrayList <String> (); for ( int i = 0; i < args.length; i++ ) l.add( args[ i ] ); Collections.sort( l ); System.out.println( l ); 33 ส งข อม ลให โปรแกรมทาง command line ตอนส งร นโปรแกรม เช น java SortDemo One Two Three Four Five 34 Arrays It is too bad that arrays are not collections You loose all of the power provided by the collection framework The class Arrays contains various methods for manipulating arrays (such as sorting and searching) It also contains methods that allows arrays to be viewed as lists. ต วอย างการใช เมท อด sort ของคลาส Arrays import java.util.*; public class ArraysSortDemo { public static void main( String args[] ) { Arrays.sort( args ); List l = Arrays.asList( args ); System.out.println( l ); 35 ส งข อม ลให โปรแกรมทาง command line ตอนส งร นโปรแกรม เช น java ArraysSortDemo One Two Three Four Five 36

10 Other Algorithms Other algorithms provided by the Collections class include Shuffling Data manipulation reverse() fill() copy() Searching Finding extreme values max() min() What About User Objects? The Collections framework will work with any Java class You need to be sure you have defined equals() hashcode() compareto() Don t use mutable objects for keys in a Map hashcode() hashcode()returns distinct integers for distinct objects. If two objects are equal according to the equals() method, then the hashcode() method on each of the two objects must produce the same integer result. When hashcode() is invoked on the same object more than once, it must return the same integer, provided no information used in equals comparisons has been modified. It is not required that if two objects are unequal according to equals()that hashcode() must return distinct integer values. Interface Comparable This ordering is referred to as the class's natural ordering, and the class's compareto() method is referred to as its natural comparison method. A class's natural ordering is said to be consistent with equals if and only if (e1.compareto((object)e2)==0) has the same boolean value as: e1.equals((object)e2) for every e1 and e2 of class C

11 import java.util.*; ต วอย างคลาส Name ท ใช ก บ collection ได public class Name implements Comparable { private String first; private String last; public Name( String firstname, String lastname ) { first = firstname; last = lastname; public String getfirst() { return first; คลาส Name (ต อ) public boolean equals( Object o ) { boolean retval = false; if (o!=null && o instanceof Name ) { Name n = ( Name )o; retval = n.getfirst().equals( first ) && n.getlast().equals( last ); return retval; public int hashcode() { return first.hashcode() + last.hashcode(); public String getlast() { return last; public String tostring() { return first + " " + last; public int compareto( Object o ) throws ClassCastException { int retval; Name n = ( Name ) o; คลาส Name (ต อ) retval = last.compareto( n.getlast() ); if ( retval == 0 ) retval = first.compareto( n.getfirst() ); ต วอย างการนำคลาส Name ไปใช ก บ collection class SortNameDemo { // run this class to test Name class public static void main( String args[] ) { List <Name> l = new ArrayList <Name> (); l.add( new Name("Sombat", "Maimee")); l.add( new Name("Somsri", "Deejing")); l.add( new Name("Amorn", "Nonnan")); l.add( new Name("Pichai", "Maimee")); Collections.sort( l ); return retval; //Name ต ว การเปร ยบเท ยบอ อบเจกต น ให ความสำค ญก บนามสก ล มากกว า ช อ จ งเปร ยบเท ยบ นามสก ลก อน ถ านามสก ลเด ยวก นจ งจะไปเปร ยบเท ยบช อ ถ าต องการให ความสำค ญก บช อ มากกว า นามสก ล จะแก ไข 43 ต วอย างน อย างไร? System.out.println( l ); ผลล พธ จากการร น จะเร ยงตามนามสก ลก อนแล วจ งเร ยงช อ [Somsri Deejing, Pichai Maimee, Sombat Maimee, Amorn Nonnan] 44

12 Tutorials Java Collections Framework Tutorial ม ล งค อย ในเว บว ชาน ท หน า Link ดาวน โหลดต วอย างโปรแกรมพร อมคำอธ บายได ท 45

IS311. Java Collections Framework (ต อ)

IS311. Java Collections Framework (ต อ) IS311 Java Collections Framework (ต อ) 1 Collections Collections are holders that let you store and organize objects in useful ways for efficient access. In the package java.util, there are interfaces

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

Collections. The Java Collections Framework. The Interfaces

Collections. The Java Collections Framework. The Interfaces Collections A collection (sometimes called a container) is an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit data

More information

Sets and Maps. Part of the Collections Framework

Sets and Maps. Part of the Collections Framework Sets and Maps Part of the Collections Framework The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection int size( ); boolean isempty( ); boolean contains(object

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

Framework in Java 5. DAAD project Joint Course on OOP using Java

Framework in Java 5. DAAD project Joint Course on OOP using Java Topic XXX Collections Framework in Java 5 DAAD project Joint Course on OOP using Java Humboldt University Berlin, University of Novi Sad, Polytehnica University of Timisoara, University of Plovdiv, University

More information

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com 2 Disclaimer & Acknowledgments Even though Sang Shin is a full-time employee

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/

More information

An Interface with Generics

An Interface with Generics Generics CSC207 Software Design Generics An Interface with Generics Generics class foo introduces a class with a type parameter T. introduces a type parameter that is required to be

More information

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

More information

CMSC 202. Containers

CMSC 202. Containers CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.

More information

CMSC 202H. Containers and Iterators

CMSC 202H. Containers and Iterators CMSC 202H Containers and Iterators Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects Arrays are compiler-supported

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Collections (Java) Collections Framework

Collections (Java) Collections Framework Collections (Java) https://docs.oracle.com/javase/tutorial/collections/index.html Collection an object that groups multiple elements into a single unit. o store o retrieve o manipulate o communicate o

More information

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data 1 JAVA PROGRAMMERS GUIDE LESSON 1 File: JGuiGuideL1.doc Date Started: July 10, 2000 Last Update: Jan 2, 2002 Status: proof DICTIONARIES, MAPS AND COLLECTIONS We have classes for Sets, Lists and Maps and

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net MULTIVARIATE TREES 2 Multivariate Trees general class of trees nodes can have any number of children

More information

COMP6700/2140 Abstract Data Types: Queue, Set, Map

COMP6700/2140 Abstract Data Types: Queue, Set, Map COMP6700/2140 Abstract Data Types: Queue, Set, Map Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 19 April 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140

More information

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know Organizing Data Data Structures that we know 17 Java Collections Generic Types, Iterators, Java Collections, Iterators Today: Arrays Fixed-size sequences Strings Sequences of characters Linked Lists (up

More information

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock) Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Collections and Maps

Collections and Maps Collections and Maps Comparing Objects The majority of the non-final methods of the Object class are meant to be overridden. They provide general contracts for objects, which the classes overriding the

More information

A simple map: Hashtable

A simple map: Hashtable Using Maps A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put(key, value); To retrieve a value from

More information

Collections Framework: Part 2

Collections Framework: Part 2 Collections Framework: Part 2 Computer Science and Engineering College of Engineering The Ohio State University Lecture 18 Collection Implementations Java SDK provides several implementations of Collection

More information

Java collections framework

Java collections framework Java collections framework Commonly reusable collection data structures Java Collections Framework (JCF) Collection an object that represents a group of objects Collection Framework A unified architecture

More information

Java Collections Framework reloaded

Java Collections Framework reloaded Java Collections Framework reloaded October 1, 2004 Java Collections - 2004-10-01 p. 1/23 Outline Interfaces Implementations Ordering Java 1.5 Java Collections - 2004-10-01 p. 2/23 Components Interfaces:

More information

IS311. Data Structures and Java Collections

IS311. Data Structures and Java Collections IS311 Data Structures and Java Collections 1 Algorithms and Data Structures Algorithm Sequence of steps used to solve a problem Operates on collection of data Each element of collection -> data structure

More information

Topic 10: The Java Collections Framework (and Iterators)

Topic 10: The Java Collections Framework (and Iterators) Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description java.lang Interface Iterable Type Parameters: T - the type of elements returned by the iterator Iterator iterator() Returns an iterator over a set of elements of type T. java.util Interface Iterator

More information

Java collections framework

Java collections framework Java collections framework Commonly reusable collection data structures Abstract Data Type ADTs store data and allow various operations on the data to access and change it ADTs are mathematical models

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net Sorting Tree Balancing A sorted tree is balanced iff for each node holds: Math.abs(size(node.left)

More information

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface Java Collections Framework Collection: a group of elements Based Design: Software 1 with Java Java Collections Framework s s Algorithms Recitation No. 6 (Collections) 2 Collection s Online Resources Collection

More information

Administrivia. CSSS Movie Night: Zombieland & Iron Man Date: Thurs., Mar 11 Time: 6 10 pm Location: DMP 310 Free pop & popcorn for every attendee!

Administrivia. CSSS Movie Night: Zombieland & Iron Man Date: Thurs., Mar 11 Time: 6 10 pm Location: DMP 310 Free pop & popcorn for every attendee! Department of Computer Science Undergraduate Events Events this week Drop-In Resume and Cover Letter Editing (20 min. appointments) Date: Thurs., March 11 Time: 11:30 am 2:30 pm Location: Rm 255, ICICS/CS

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Generics and collections

Generics and collections Generics From JDK 1.5.0 They are similar to C++ templates They allow to eliminate runtime exceptions related to improper casting (ClassCastException) Traditional approach public class Box { private Object

More information

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code. Lecture 15 Summary Collections Framework Iterable, Collections, Set Map Collections class Comparable and Comparator By the end of this lecture, you will be able to use different types of Collections and

More information

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc. Contents Topic 08 - Collections I. Introduction - Java Collection Hierarchy II. Choosing/using collections III. Collection and Iterator IV. Methods of Collection V. Concrete classes VI. Implementation

More information

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Model Solutions COMP 103: Test

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

Collections and Maps

Collections and Maps Software and Programming I Collections and Maps Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Array Lists Enhanced for Loop ArrayList and LinkedList Collection Interface Sets and

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University C O P Y R I G H T S 2 0 1 5 E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D - Containers - About Containers

More information

Principles of Software Construction: Objects, Design and Concurrency. More design patterns and Java Collections. toad

Principles of Software Construction: Objects, Design and Concurrency. More design patterns and Java Collections. toad Principles of Software Construction: Objects, Design and Concurrency 15-214 toad More design patterns and Java Collections Spring 2013 Christian Kästner Charlie Garrod School of Computer Science 2012-13

More information

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

Overview$of$Collection$and$Map$Types

Overview$of$Collection$and$Map$Types Java$API$Extract:$Collection,$Map,$ Functional$Interfaces$and$Streams (JDK$1.2$or$laterD$presentation$is$not$complete!)! Overview of Collection$and Map Types! Iterable,$Iterator and ListIterator! Collection!

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

EXAMINATIONS 2017 TRIMESTER 2

EXAMINATIONS 2017 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2017 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

Introduction to Collections

Introduction to Collections Module 3 COLLECTIONS Introduction to Collections > A collection sometimes called a container is simply an object that groups multiple elements into a single unit. > Collections are used to store, retrieve,

More information

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

27/04/2012. Objectives. Collection. Collections Framework. Collection Interface. Collection algorithm. Legacy collection Objectives Collection Collections Framework Concrete collections Collection algorithm By Võ Văn Hải Faculty of Information Technologies Summer 2012 Legacy collection 1 2 2/27 Collections Framework "Collection"

More information

JAVA. java.lang.stringbuffer java.lang.stringbuilder

JAVA. java.lang.stringbuffer java.lang.stringbuilder JAVA java.lang.stringbuffer java.lang.stringbuilder 1 Overview mutable string instances of String are immutable do not extend String String, StringBuffer, StringBuilder are final StringBuffer safe for

More information

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2016 CSC 321: Data Structures Fall 2016 Balanced and other trees balanced BSTs: AVL trees, red-black trees TreeSet & TreeMap implementations heaps priority queue implementation heap sort 1 Balancing trees recall:

More information

CSC 321: Data Structures. Fall 2017

CSC 321: Data Structures. Fall 2017 CSC 321: Data Structures Fall 2017 Balanced and other trees balanced BSTs: AVL trees, red-black trees TreeSet & TreeMap implementations heaps priority queue implementation heap sort 1 Balancing trees recall:

More information

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14 MINI-MAX USING TREES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 Spring 2014 2 Important Dates. April 10 --- A4 due (Connect 4, minimax, trees) April 15 --- A5 due (Exercises on different topics,

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

תוכנה 1 מבני נתונים גנריים

תוכנה 1 מבני נתונים גנריים תוכנה 1 מבני נתונים גנריים תרגול 8 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2 Online Resources

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

Software 1 with Java. Recitation No. 6 (Collections)

Software 1 with Java. Recitation No. 6 (Collections) Software 1 with Java Recitation No. 6 (Collections) Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2

More information

The Java Collections Framework and Lists in Java Parts 1 & 2

The Java Collections Framework and Lists in Java Parts 1 & 2 The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering

More information

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces Taking Stock IE170: Algorithms in Systems Engineering: Lecture 7 Jeff Linderoth Department of Industrial and Systems Engineering Lehigh University January 29, 2007 Last Time Practice Some Sorting Algs

More information

Practical Session 3 Java Collections

Practical Session 3 Java Collections Practical Session 3 Java Collections 1 Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack Maps The Collections class Wrapper classes 2 Collection

More information

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework Announcements Abstract data types (again) PS 5 ready Tutoring schedule updated with more hours Today s topic: The Java Collections Framework Reading: Section 7.5 An ADT is a model of a collection of data

More information

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 April 2, 2014 Generics and CollecCons Midterm 2 is Friday Announcements Towne 100 last names A - L DRLB A1 last names M - Z Review sessions: Tonight!

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Implementations I 1 Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Stack and queues Array-based implementations

More information

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 Trimester 1, MID-TERM TEST COMP103 Introduction

More information

Tables and Priority Queues

Tables and Priority Queues Chapter 12 Tables and Priority Queues 2011 Pearson Addison-Wesley. All rights reserved 12 A-1 The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that

More information

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM Time Allowed: TWO HOURS ********

More information

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) What is a Data Structure? Introduction A data structure is a particular way of organizing data using one or

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1 COMP209 Object Oriented Programming Container Classes 3 Mark Hall List Functionality Types List Iterator Adapter design pattern Adapting a LinkedList to a Stack/Queue Map Functionality Hashing Performance

More information

תוכנה 1 מבני נתונים גנריים

תוכנה 1 מבני נתונים גנריים תוכנה 1 מבני נתונים גנריים תרגול 8 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 3 Online Resources

More information

Tables and Priority Queues!

Tables and Priority Queues! Chapter 12! Tables and Priority Queues! 2011 Pearson Addison-Wesley. All rights reserved 12 A-1 2015-11-30 21:52:31 1/49 Chapter-12.pdf (#14) The ADT Table The ADT table, or dictionary! Uses a search key

More information

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

EPITA Première Année Cycle Ingénieur. Atelier Java - J2 EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr http://www.lse.epita.fr Plan 1 2 A Solution: Relation to ML Polymorphism 3 What are Collections Collection Core Interface Specific Collection

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 March 23 rd, 2016 Generics and Collections Chapter 25 HW #6 due Tuesday Announcements I will be away all next week (FP workshop in Germany) Monday's

More information

Collection ArrayList<T> Collection Collection

Collection ArrayList<T> Collection Collection Collection ArrayList Collection Collection Adapted from material by Walter Savitch Adapted from material by Walter Savitch public void method(string arg1, ArrayList arg2) String ArrayList Adapted

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 Mar 23, 2012 Generics, CollecBons and IteraBon Announcements CIS Course Faire TODAY at 3PM, here HW08 is due on Monday, at 11:59:59pm Midterm 2

More information

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework SUMMARY COLLECTIONS FRAMEWORK PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 Introduction Collections and

More information

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION

More information

JAVA. java.lang.stringbuffer java.lang.stringbuilder

JAVA. java.lang.stringbuffer java.lang.stringbuilder JAVA java.lang.stringbuffer java.lang.stringbuilder 1 Overview mutable string instances of String are immutable do not extend String String, StringBuffer, StringBuilder are final StringBuffer safe for

More information

Charlie Garrod Bogdan Vasilescu

Charlie Garrod Bogdan Vasilescu Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 2: Designing (sub-) systems Java Collec9ons design case study Charlie Garrod Bogdan Vasilescu School of Computer Science 1 Administrivia

More information

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 45 minutes

More information

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS ** Family Name:.............................. Other Names:...................................... Signature.................................. COMP 103 : Test 2019, Jan 9 ** WITH SOLUTIONS ** Instructions Time

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 March 28, 2018 Java Generics Collections and Equality Chapters 25 & 26 Announcements HW7: Chat Server Available on Codio / Instructions on the web

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 6. The Master Theorem. Some More Examples...

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 6. The Master Theorem. Some More Examples... Taking Stock IE170: Algorithms in Systems Engineering: Lecture 6 Jeff Linderoth Last Time Divide-and-Conquer The Master-Theorem When the World Will End Department of Industrial and Systems Engineering

More information

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 MID YEAR COMP103 Introduction to Data

More information

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel) Programmieren II Collections Alexander Fraser fraser@cl.uni-heidelberg.de (Based on material from T. Bögel) May 28, 2014 1 / 46 Outline 1 Recap Paths and Files Exceptions 2 Collections Collection Interfaces

More information

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java CS2110: Software Development Methods Maps and Sets in Java These slides are to help with the lab, Finding Your Way with Maps This lab uses Maps, and Sets too (but just a little). Readings from textbook:

More information

Chapter 5 Java Collection. j a v a c o s q q. c o m X i a n g Z h a n g

Chapter 5 Java Collection. j a v a c o s q q. c o m X i a n g Z h a n g Chapter 5 Java Collection j a v a c o s e @ q q. c o m X i a n g Z h a n g Content 2 Arrays Collection ArrayList LinkedList Map HashMap Iterator COSE Java Array Declaration and Assignment of an Array:

More information

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures Abstract Data Types (ADTs) Class #08: Linear Data Structures Software Design III (CS 340): M. Allen, 08 Feb. 16 An ADT defines a kind of computational entity: A set of objects, with possible values A set

More information

1.00/ Introduction to Computers and Engineering Problem Solving. Final Exam / December 21, 2005

1.00/ Introduction to Computers and Engineering Problem Solving. Final Exam / December 21, 2005 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Exam / December 21, 2005 Name: Email Address: TA: Section: You have 180 minutes to complete this exam. For coding questions, you

More information

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList!

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList! Implementations I 1 Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList! Stack and queues Array-based implementations

More information